package main

import (
	"fmt"
	"log"
	"net/http"
)

func main() {
	log.Printf("Starting WebSocket server with config: %+v", config)
	log.Printf("Proto command codes: HeartbeatReq=%d, HeartbeatResp=%d, LoginReq=%d, LoginResp=%d",
		ProtoCmds.CmdHeartbeatReq, ProtoCmds.CmdHeartbeatResp,
		ProtoCmds.CmdLoginReq, ProtoCmds.CmdLoginResp)

	// 设置HTTP路由
	http.HandleFunc("/", handleHome)
	http.HandleFunc("/ws", handleWebSocket)

	// 启动HTTP服务器
	log.Printf("Server listening on port %s", config.Port)
	if err := http.ListenAndServe(":"+config.Port, nil); err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

// 处理首页请求
func handleHome(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	// 动态生成HTML，显示当前自动获取的命令码
	html := fmt.Sprintf(`
		<!DOCTYPE html>
		<html>
		<head>
			<meta charset="UTF-8">
			<title>WebSocket 服务器</title>
			<style>
				body { font-family: Arial, sans-serif; margin: 40px; line-height: 1.6; }
				h1 { color: #333; }
				.container { max-width: 800px; margin: 0 auto; }
				.info { background-color: #f4f4f4; padding: 20px; border-radius: 5px; }
				table { border-collapse: collapse; width: 100%%; margin-top: 20px; }
				th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
				th { background-color: #f2f2f2; }
				tr:nth-child(even) { background-color: #f9f9f9; }
			</style>
		</head>
		<body>
			<div class="container">
				<h1>WebSocket 服务器</h1>
				<div class="info">
					<p>服务器已启动，可以通过以下地址连接：</p>
					<p><code>ws://127.0.0.1:9020/ws</code></p>
					<p>支持的功能及命令码：</p>
					<table>
						<tr>
							<th>功能</th>
							<th>请求命令码</th>
							<th>响应命令码</th>
						</tr>
						<tr>
							<td>心跳</td>
							<td>%d</td>
							<td>%d</td>
						</tr>
						<tr>
							<td>登录</td>
							<td>%d</td>
							<td>%d</td>
						</tr>
					</table>
					<p><small>注：命令码是从proto文件的option (com.lin.proto.cmd)自动获取的</small></p>
				</div>
			</div>
		</body>
		</html>
	`, ProtoCmds.CmdHeartbeatReq, ProtoCmds.CmdHeartbeatResp,
		ProtoCmds.CmdLoginReq, ProtoCmds.CmdLoginResp)

	w.Write([]byte(html))
}
